package com.xinxing.learning.security.config;

import com.xinxing.learning.security.filter.CaptchaFilter;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

@Slf4j
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Bean
    public UserDetailsService userDetailsService() {
        InMemoryUserDetailsManager inMemoryUserDetailsManager = new InMemoryUserDetailsManager();
        inMemoryUserDetailsManager.createUser(User.withUsername("root").password("{noop}123").roles("admin", "supper").build());
        return inMemoryUserDetailsManager;
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService());
    }

    @Override
    @Bean
    protected AuthenticationManager authenticationManager() throws Exception {
        return super.authenticationManager();
    }

    @SneakyThrows
    @Bean
    public CaptchaFilter captchaFilter() {
        CaptchaFilter captchaFilter = new CaptchaFilter();
        captchaFilter.setUsernameParameter("uname");
        captchaFilter.setPasswordParameter("pwd");
        captchaFilter.setCaptchaParameter("captcha");
        captchaFilter.setFilterProcessesUrl("/doLogin");
        captchaFilter.setAuthenticationManager(authenticationManager());
        captchaFilter.setAuthenticationSuccessHandler((req, resp, authentication) -> {
            resp.sendRedirect("/index.html");
        });
        captchaFilter.setAuthenticationFailureHandler((req, resp, ex) -> {
            // 无括号 不能打印出任何异常信息
            // log.error("captchaFilter() called with exception => ", ex.getMessage());
            // 无括号 能正常打印出异常信息 包括异常堆栈信息
            log.error("captchaFilter() called with exception => ", ex);
            // 有括号 能打印出异常信息的消息
            // log.error("captchaFilter() called with exception => {}", ex.getMessage());
            // 有括号 能正常打印出异常信息 包括异常堆栈信息
            // log.error("captchaFilter() called with exception => {}", ex);
            resp.sendRedirect("/login.html");
        });
        return captchaFilter;
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .mvcMatchers("/login.html").permitAll()
                .mvcMatchers("/captcha").permitAll()
                .anyRequest().authenticated()
                .and()
                .formLogin()
                .loginPage("/login.html")
                .and()
                .logout()
                .logoutUrl("/logout")
                .and()
                .csrf().disable()
        ;
        http.addFilterAt(captchaFilter(), UsernamePasswordAuthenticationFilter.class);
    }
}
